package com.lzh.hosp.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzh.hosp.listener.ScheduleListener;
import com.lzh.hosp.model.Doctor;
import com.lzh.hosp.model.OrderInfo;
import com.lzh.hosp.model.ResponseResult;
import com.lzh.hosp.model.Schedule;
import com.lzh.hosp.model.dto.ScheduleQueryDto;
import com.lzh.hosp.service.DictService;
import com.lzh.hosp.service.OrderInfoService;
import com.lzh.hosp.service.ScheduleService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/sche")
@Tag(name="排班管理")
public class ScheduleController {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private DictService dictService;

    @Autowired
    private OrderInfoService orderInfoService;

    //添加排班
    @PostMapping("add")
    @PreAuthorize("hasAuthority('sys:schedule:add')")
    public ResponseResult add(@RequestBody @Validated Schedule schedule){
        boolean flag = scheduleService.add(schedule);
        if (flag==false){
            return ResponseResult.fail("添加失败");
        }
        return ResponseResult.ok();
    }

    //删除排班
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:schedule:delete')")
    public ResponseResult delete(@PathVariable Long id){
        Schedule schedule = scheduleService.getById(id);
        boolean flag = scheduleService.removeById(id);
        if (flag){//将已经支付的预约订单状态设置为订单取消
            QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("schedule_id",schedule.getId());
            List<OrderInfo> list = orderInfoService.list(wrapper);
            for (OrderInfo orderInfo : list) {
                orderInfo.setOrderStatus(3);//3表示订单取消
                orderInfo.setCancelReason("排班取消，请另选排班");
                orderInfoService.updateById(orderInfo);
            }
        }
        return flag?ResponseResult.ok():ResponseResult.fail("删除失败");
    }

    //批量删除排班
    @DeleteMapping("/batchDelete")
    @PreAuthorize("hasAuthority('sys:schedule:delete')")
    public ResponseResult batchDelete(@RequestBody Long[] ids){
        boolean flag = scheduleService.removeByIds(Arrays.asList(ids));
        return flag?ResponseResult.ok():ResponseResult.fail("批量删除失败");
    }

    //更新排班
    @PostMapping("update")
    @PreAuthorize("hasAuthority('sys:schedule:update')")
    public ResponseResult update(@RequestBody @Validated Schedule schedule){
        boolean flag = scheduleService.updateById(schedule);
        return flag?ResponseResult.ok(true): ResponseResult.fail("更新失败");
    }

    //批量添加排班
    @PostMapping("batchAdd")
    @PreAuthorize("hasAuthority('sys:schedule:add')")
    @Transactional
    public ResponseResult batchAdd(MultipartFile file) throws IOException {
            String originalFilename = file.getOriginalFilename();
            int begin = originalFilename.indexOf(".");
            int last = originalFilename.length();
            String fileType = file.getOriginalFilename().substring(begin,last);
            EasyExcel.read(file.getInputStream(), Schedule.class, new ScheduleListener(scheduleService)).sheet().doRead();

        return ResponseResult.ok();
    }

    //多条件查询排班
    @PostMapping("find")
    public ResponseResult find(@RequestBody ScheduleQueryDto scheduleQueryDto){
        List<Schedule> list = scheduleService.get(scheduleQueryDto);
        return ResponseResult.ok(list);
    }

    //查询出往后14天的日期
    @GetMapping("find14Day")
    public ResponseResult find14Day(){
        List<String> list = scheduleService.get14Day();
        return ResponseResult.ok(list);
    }

    //根据医生编号查询出最近有排班的日期
    @GetMapping("findRecentDayByDocId/{docId}")
    public ResponseResult findRecentDayByDocId(@PathVariable Long docId){
        List<JSONObject> list = scheduleService.getRecentDayByDocId(docId);
        return ResponseResult.ok(list);
    }

    //根据科室编号和最近14天的安排，查询出医生列表
    @GetMapping("findRecently/{depcode}")
    public ResponseResult findRecently(@PathVariable Long depcode){
        List<Doctor> list = scheduleService.findRecently(depcode);
        return ResponseResult.ok(list);
    }


    //根据对应日期和编号查询对应的医生列表
    @GetMapping("findByDepcodeAndWorkDate")
    public ResponseResult findByDepAndDate(ScheduleQueryDto scheduleQueryDto){
        List<Doctor> list =scheduleService.findByDepcodeAndWorkDate(scheduleQueryDto);
        return ResponseResult.ok(list);
    }

    //根据id查询排班
    @GetMapping("info/{id}")
    public ResponseResult info(@PathVariable Long id){
        Schedule schedule = scheduleService.getById(id);

        //设置其他值
        Long parentValue = dictService.getParentValue(schedule.getDepcode());
        Long[] defaultCode = {parentValue,schedule.getDepcode()};
        Map<String,Object> params = new HashMap<>();
        params.put("defaultCode",defaultCode);
        schedule.setParams(params);
        return ResponseResult.ok(schedule);
    }

}
